package com.ly.push.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ly.push.param.OtherProperties;
import com.ly.push.param.weather.WeatherInfo;
import com.ly.push.param.weather.WeatherInfo1;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 天气，可以使用List集合一下输出好几天的，自己拼装就行
 */
@Component
public class WeatherUtils {

    @Resource
    OtherProperties otherProperties;

    public  WeatherInfo getWeather(String cityName){
        return getWeather(cityName,null);
    }
    //明天的天气,后天的天气(最多显示5天，所以index为：0，1，2，3，4)
    public  WeatherInfo getWeather(String cityName,Integer index){
        if (null == index){
            index = 0;
        }
        if (cityName.contains("省")){
            cityName = cityName.substring(cityName.indexOf("省")+1);
        }
        if (cityName.contains("市")){
            cityName = cityName.substring(0,cityName.indexOf("市"));
        }
        String key = otherProperties.getWeatherkey();
        String data = HttpUtils.doGet("https://apis.juhe.cn/simpleWeather/query?key="+key+"&city="+cityName);
        WeatherInfo weatherInfo = new WeatherInfo();
        JSONObject jsonObject = JSONObject.parseObject(data.toString());
        String reason = jsonObject.getString("reason");
        if (reason.contains("查询成功")){
            JSONObject jsonObject1 = jsonObject.getJSONObject("result");
            JSONObject jsonObject2 = jsonObject1.getJSONObject("realtime");
            String power = jsonObject2.getString("power");
            String future = jsonObject1.getString("future");
            List<WeatherInfo1> list = JSONArray.parseArray(future,WeatherInfo1.class);
            WeatherInfo1 weatherInfo1 = new WeatherInfo1();
            //显示未来五天的，0明天，1后天...
            weatherInfo1 = list.get(index);
            weatherInfo.setDate(weatherInfo1.getDate());
            weatherInfo.setType(weatherInfo1.getWeather());
            weatherInfo.setFengli(power);
            weatherInfo.setFengxiang(weatherInfo1.getDirect());
            String temperature = weatherInfo1.getTemperature();//123/456°C
            String high = temperature.substring(temperature.indexOf("/")+1,temperature.length());
            String low = temperature.substring(0,temperature.indexOf("/"))+"°C";
            weatherInfo.setLow(low);
            weatherInfo.setHigh(high);
            return weatherInfo;
        }
        return null;
    }


}
